<?php

namespace app\common\service;

use Workerman\Connection\AsyncTcpConnection;
use Workerman\Connection\TcpConnection;
use Workerman\Worker;

class WebSocketService
{
    protected $websocketServerUrl = 'wss://172.16.30.57:2346';

    public static function sendToWebSocketServer( $message)
    {
        $worker = new Worker();
        $worker->count = 1;
        $worker->onWorkerStart = function ($worker) use ($message) {
            // 连接到 WebSocket 服务器

            $connection = new TcpConnection($this->websocketServerUrl);
            $connection->onConnect = function ($connection) use ($message){
                // 连接建立成功后发送消息
                $connection->send($message);
                $connection->close(); // 发送完成后立即关闭连接
            };
            // 启动连接
            $connection->connect();


        };

        // 启动 Worker
        Worker::runAll();
    }
}
